<template>
  <div class="min-h-screen flex flex-col">
    <main class="flex-grow container mx-auto">
      <div class="bg-white rounded-lg p-4 card-shadow mb-6">
        <div class="flex items-center justify-between mb-4">
          <div class="flex space-x-2">
            <el-button
              v-for="(form, index) in forms"
              :key="form.id"
              :type="currentFormIndex === index ? 'primary' : 'default'"
              @click="switchForm(form)"
            >
              {{ form.name }}
            </el-button>
          </div>
        </div>

        <div class="bg-white rounded-lg p-4 card-shadow mb-6 mt-6">
          <div class="flex flex-wrap gap-4 mb-4" style="margin-top: 10px">
            <!-- <el-button @click="selectAllFields" type="primary">全选</el-button>
            <el-button @click="deselectAllFields" type="default"
              >取消全选</el-button
            > -->
            <el-button @click="batchSetFields('isDisplay', true)" type="success"
              >全部设为显示</el-button
            >
            <el-button
              @click="batchSetFields('isDisplay', false)"
              type="warning"
              >全部设为隐藏</el-button
            >
            <el-button
              @click="batchSetFields('isRequired', true)"
              type="success"
              >全部设为必填</el-button
            >
            <el-button
              @click="batchSetFields('isRequired', false)"
              type="warning"
              >全部设为不可选</el-button
            >
            <el-button @click="batchSetFields('isModify', true)" type="info"
              >全部设为可修改</el-button
            >
            <el-button @click="batchSetFields('isModify', false)" type="danger"
              >全部设为不可修改</el-button
            >
          </div>

          <el-table
            :data="tableFields"
            border
            stripe
            highlight-current-row
            @selection-change="handleSelectionChange"
            ref="fieldTable"
          >
            <el-table-column
              prop="comments"
              label="字段标签"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="columnName"
              label="字段名称"
              width="120"
            ></el-table-column>
            <el-table-column label="是否显示">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isDisplay"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleFieldChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="是否必填">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isRequired"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleFieldChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="是否可修改">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isModify"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleFieldChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { getField } from "@/api/flowable/gather.js";

export default {
  name: "FormFieldConfigurator",
    // 可接收外部传入的表单配置
   props: {
    initialForms: {
      type: Array,
      default: () => []
    }
  
  },
  data() {
    return {
       forms: this.initialForms.length ? this.initialForms : [
        { id: 1, name: "基本信息表", activeName: "userForm", fields: [] },
        { id: 2, name: "家庭基本信息", activeName: "familyForm", fields: [] },
        { id: 3, name: "获奖情况", activeName: "awadForm", fields: [] }
      ],
      currentFormIndex: 0,
      selectedFields: [], // 当前选中的字段
      loading: false,
        selectedFieldMap: {} // 用于保存选中状态（跨表单切换时记忆）
    };
  },
  computed: {
    currentForm() {
      return this.forms[this.currentFormIndex] || {};
    },
    tableFields() {
      return this.currentForm.fields || [];
    },
  },
  created() {
    this.initForms();
  },
  watch: {
    initialForms: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.forms = JSON.parse(JSON.stringify(newVal)); // 深拷贝避免引用问题
        this.initForms();
      }
    }
  },
  methods: {
    // 初始化表单数据
    initForms() {
      // 重置表单加载状态
      this.formLoading = {};
      
      // 检查并加载空表单
      this.forms.forEach(form => {
        if (form.fields && form.fields.length === 0 && form.activeName) {
          this.formLoading[form.id] = true;
          this.loadFormFields(form);
        } else {
          this.formLoading[form.id] = false;
        }
      });
    },

    // 加载单个表单字段
    async loadFormFields(form) {
      try {
        const res = await getField({ formType: form.activeName });
        form.fields = res.data.map(item => ({
          ...item,
          isDisplay: item.isDisplay ?? false,
          isRequired: item.isRequired ?? false,
          isModify: item.isModify ?? false,
          _original: {
            isDisplay: item.isDisplay ?? false,
            isRequired: item.isRequired ?? false,
            isModify: item.isModify ?? false,
          }
        }));
      } catch (error) {
        console.error(`加载${form.name}数据失败:`, error);
        this.$message.error(`加载${form.name}数据失败`);
        form.fields = [];
      } finally {
        this.formLoading[form.id] = false;
        
        // 如果当前正在显示该表单，刷新选择状态
        if (this.currentForm.id === form.id) {
          this.refreshSelection();
        }
      }
    },

    // 刷新选择状态
    refreshSelection() {
      this.$nextTick(() => {
        const selectedIds = this.selectedFieldMap[this.currentForm.id] || [];
        this.tableFields.forEach(row => {
          if (selectedIds.includes(row.id)) {
            this.$refs.fieldTable.toggleRowSelection(row, true);
          }
        });
      });
    },
 // 优化表单切换逻辑
    async switchForm(form) {
      // 防止重复切换相同表单
      if (this.currentForm.id === form.id) return;
      
      // 保存当前选中状态
      this.selectedFieldMap[this.currentForm?.id] = this.selectedFields.map(f => f.id);
      
      const index = this.forms.findIndex(f => f.id === form.id);
      if (index === -1) return;

      this.currentFormIndex = index;
      
      // 如果表单数据为空且未在加载中，则加载数据
      if (form.fields.length === 0 && form.activeName && !this.formLoading[form.id]) {
        this.formLoading[form.id] = true;
        await this.loadFormFields(form);
      } else {
        // 数据已存在或正在加载，直接刷新选择状态
        this.refreshSelection();
      }

      this.$message.success(`已切换到 ${form.name}`);
    },

    // async loadFormFields(form) {
    //   try {
    //     const res = await getField({ formType: form.activeName });
    //     form.fields = res.data.map((item) => ({
    //       ...item,
    //       // 初始化字段状态
    //       isDisplay: item.isDisplay !== undefined ? item.isDisplay : false,
    //       isRequired: item.isRequired !== undefined ? item.isRequired : false,
    //       isModify: item.isModify !== undefined ? item.isModify : false,
    //       // 保存原始值用于重置
    //       _original: {
    //         isDisplay: item.isDisplay !== undefined ? item.isDisplay : false,
    //         isRequired: item.isRequired !== undefined ? item.isRequired : false,
    //         isModify: item.isModify !== undefined ? item.isModify : false,
    //       },
          
    //     }));
        
    //   } catch (error) {
    //     console.error(`加载${form.name}数据失败:`, error);
    //     this.$message.error(`加载${form.name}数据失败`);
    //     form.fields = [];
    //   }
    // },

    // async switchForm(form) {
    //   console.log(form, "触发了");
    //   // 保存当前表单的选中状态
    //   this.selectedFieldMap[this.currentForm.id] = this.selectedFields.map(
    //     (field) => field.id
    //   );

    //   const index = this.forms.findIndex((f) => f.id === form.id);
    //   if (index !== -1) {
    //     this.currentFormIndex = index;

    //     // 如果该表单还没有加载过数据，则加载
    //     if (this.tableFields.length === 0) {
    //       await this.loadFormFields(this.currentForm);
    //     }

    //     // 恢复新表单的选中状态
    //     this.$nextTick(() => {
    //       const selectedIds = this.selectedFieldMap[form.id] || [];
    //       if (selectedIds.length > 0) {
    //         this.tableFields.forEach((row) => {
    //           if (selectedIds.includes(row.id)) {
    //             this.$refs.fieldTable.toggleRowSelection(row, true);
    //           }
    //         });
    //       }
    //     });

    //     this.$message.success(`已切换到 ${this.currentForm.name}`);
    //     console.log("selectedFieldMap", this.selectedFieldMap[form.id]);
    //   }
    // },
    //   const index = this.forms.findIndex((f) => f.id === form.id);
    //   if (index !== -1) {
    //     this.currentFormIndex = index;
    //     // 如果该表单还没有加载过数据，则加载
    //     if (this.tableFields.length === 0) {
    //       await this.loadFormFields(this.currentForm);
    //     }
    //     this.$message.success(`已切换到 ${this.currentForm.name}`);
    //   }
    // },

    // 字段选择相关方法
    handleSelectionChange(selection) {
      this.selectedFields = selection;
    },

    selectAllFields() {
      this.$refs.fieldTable.toggleAllSelection();
    },

    deselectAllFields() {
      this.$refs.fieldTable.clearSelection();
    },

    // 批量设置字段属性
    batchSetFields(prop, value) {
      const fieldsToUpdate =
        this.selectedFields.length > 0 ? this.selectedFields : this.tableFields;

      fieldsToUpdate.forEach((field) => {
        field[prop] = value;
        this.handleFieldChange(field);
      });

      const actionName = {
        isRequired: value ? "必填" : "可选",
        isModify: value ? "可编辑" : "不可编辑",
        isDisplay: value ? "显示" : "隐藏",
      }[prop];

      this.$message.success(
        this.selectedFields.length > 0
          ? `已将所选字段设为${actionName}`
          : `已将全部字段设为${actionName}`
      );
    },

    // 字段编辑相关方法
    editField(field) {
      this.$emit("edit-field", field);
      // 可以在这里打开一个对话框进行详细编辑
    },

    resetField(field) {
      if (field._original) {
        Object.assign(field, {
          isDisplay: field._original.isDisplay,
          isRequired: field._original.isRequired,
          isModify: field._original.isModify,
        });
        this.handleFieldChange(field);
        this.$message.success(`已重置字段 ${field.comments}`);
      }
    },

    // 处理字段变更
    handleFieldChange(field) {
      this.$emit("field-change", field);
      // 这里可以添加保存到后端的逻辑
    },

    // 保存相关方法
    saveCurrentForm() {
      this.$emit("save-form", this.currentForm);
      this.$message.success(`${this.currentForm.name} 配置已保存`);
    },

    saveAllForms() {
      this.$emit("save-all-forms", this.forms);
      this.$message.success("所有表单配置已保存");
    },
  },
};
</script>

<style scoped>
.card-shadow {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.transition-all-300 {
  transition: all 0.3s ease;
}

.el-table {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>